package 富婆梦.第一阶段.第七周IO流;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.TreeSet;

/**
 * @ProjectName: java-learning
 * @Package: 富婆梦.第一阶段.第七周
 * @ClassName: TestFile
 * @Author: hemengjin
 * @Description:
 * @Date:2021/9/12 9:16
 * @Version: 1.0
 */
public class TextFile extends ArrayList<String> {
    public static String read(String fileName) {
        StringBuilder sb = new StringBuilder();
        try {
            File file = new File(fileName);
            //File getAbsoluteFile(),返回此抽象路径名的绝对路径名形式
            FileReader fr = new FileReader(file.getAbsoluteFile());
            BufferedReader in = new BufferedReader(fr);
            try {
                String s;
                while ((s = in.readLine()) != null) {
                    sb.append(s);
                    sb.append("\n");
                }
            }finally {
                in.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return sb.toString();
    }

    public static void write(String fileName,String text){
        try {
            File file = new File(fileName);
            //File getAbsoluteFile(),返回此抽象路径名的绝对路径名形式
            PrintWriter out = new PrintWriter(file.getAbsoluteFile());
            try {
                out.print(text);
            }finally {
                out.close();
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    public TextFile(String fileName,String splitter){
        super(Arrays.asList(read(fileName).split(splitter)));
        if (get(0).equals("")){
            remove(0);
        }
    }

    public TextFile(String fileName){
        this(fileName,"\n");
    }

    public void write(String fileName){
        try{
            File file = new File(fileName);
            //File getAbsoluteFile(),返回此抽象路径名的绝对路径名形式
            PrintWriter out = new PrintWriter(file.getAbsoluteFile());
            try {
                for (String item:this){
                    out.println(item);
                }
            }finally {
                out.close();
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        String file = read("TextFile.java");
        write("test2.txt",file);
        TextFile text = new TextFile("test.txt");
        text.write("test2.txt");
        TreeSet<String> words = new TreeSet<String>(new TextFile("TextFile.java","\\W"));
        System.out.println(words.headSet("a"));
    }


}
